<?php
	require_once('config.php');
	require_once('db.php');
	require_once('charts/includes/FusionCharts.php');
	require_once('charts/includes/FC_Colors.php');
	require_once('charts/includes/pChart/pChart.class.php');
	require_once('charts/includes/pChart/pData.class.php');
	define('BY_DAY', 0);
	define('BY_MONTH', 1);
	define('BY_YEAR', 2);
	// disable browser cache
	header( "Expires: Mon, 20 Dec 1998 01:00:00 GMT" );
    header( "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" );
    header( "Pragma: no-cache" );
    header( "Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header( "Cache-Control: post-check=0, pre-check=0", false);
	if(isset($_POST['submit']) || isset($_POST['day_detail_submit']) || isset($_POST['hour_detail_submit'])){
		// get all post information
		$site_info = explode(":", $_POST['site']);
		$site_id = $site_info[0];
		$site_hostname = $site_info[1];
		$report_type = $_POST['type'];
		$year = $_POST['year'];
		$month = $_POST['month']+1;
		$day = $_POST['day'];
		//$graph = $_POST['graph'];
		$graph = 'image';
		$date = "";

		switch ($report_type){
			case BY_DAY:
					$date .= "$day/$month/$year";
				break;
			case BY_MONTH:
					$date .= "$month/$year";
				break;
			case BY_YEAR:
					$date .= "$year";
				break;
			default:
				break;
		}

		$message = "<div align=\"center\" style=\"width: 80%;\"><h2>"
				. "Detail report of $site_hostname. Date: $date</h2>";
		echo $message;
		echo "<div align=\"center\" style=\"width: 80%;\"><a href=\"reports.php\">Back to report selection page</a></div>";
		echo "<div align=\"center\" style=\"width: 80%;\"><a href=\"index.php\">Back to Main Menu</a></div>";
		$result = array();
		$link = connectdb($servername, $dbname, $dbusername, $dbpassword);
		if(!$link){
			echo "<div align=\"center\" width=\"100%\"><h3>Can not connect to the database<h3></div>";
			exit;
		}
		$error = '';
		// show reports based on the selected creterias.
		switch($report_type){
			case BY_DAY:{
					// get all protocols
					$protocols = get_protocols($site_id, $link, $error);
					if($protocols === false){ // failed to get protocol
						echo "<div align=\"center\" width=\"100%\"><h3>$error</h3></div>";
						exit;
					}else{
						if(count($protocols) < 1){ // there is no protocol for this site
							echo "<div align=\"center\" width=\"100%\"><h3>There has no protocol configured for this site</h3></div>";
							exit;
						}
						foreach($protocols as $protocol){ // draw one chart for each protocol
							$error = '';
							$records = get_checking_records_by_day($site_id, $protocol['protocol_id'], $year, $month, $day, $link, $error);
							if($records === false){
								echo "<div align=\"center\" width=\"100%\"><h3>$error</h3></div>";
								exit;
							}else{
								if(count($records) < 1){ // there is no record for this site and the protocol
									echo "<div align=\"center\" width=\"100%\"><h3>There has no checking record for protocol: " . $protocol['protocol_name'] . "</h3></div>";
									exit;
								}else{
									if($graph == "flash"){// Draw flash chart
										$minValue = 0;
										$maxValue = 0;
										echo "<SCRIPT LANGUAGE=\"Javascript\" SRC=\"charts/js/FusionCharts.js\"></SCRIPT>";
										// draw chart now
										$chart_title = "Monitoring result for protocol " . $protocol['protocol_name']
												. ". Scale: 1:" . $chart_valueScale;
										$sub_title = "Day detail";
										$strXML = "<graph caption='" . $chart_title
												. "' formatNumberScale='" . $chart_formatNumberScale
												. "' decimalPrecision='" . $chart_decimalPrecision
												. "' rotateNames='" . $chart_rotateNames;
										if($protocol['protocol_name'] == 'ICMP'){
											$strXML .= "' yAxisName= 'Response Time(ms)";
										}else{
											$strXML .= "' yAxisName= 'Fetching Time(ms)";
										}
										$strXML .= "' xAxisName= 'Start time"
											. "' baseFontSize='" . $chart_baseFontSize
											. "' yAxisMinValue='%s"
											. "'>";
											;
										$minValue = $records[0]['operating_time'];
										foreach($records as $record){
	      									$strXML .= "<set name='" . substr($record['starting_time'], 11) . "' value='" . ($record['operating_time']* $chart_valueScale) . "' colo='" . getFCColor() . "' />";
	      									//find the minimum total time to identify the yAxisMinValue
	      									if($record['operating_time'] < $minValue){
	      										$minValue = $record['operating_time'];
	      									}
	      									//find the maximum total time to identify the yAxisMaxValue
											if($record['operating_time'] > $maxValue){
	      										$maxValue = $record['operating_time'];
	      									}
										}
										$strXML = sprintf($strXML, ($minValue/2) * $chart_valueScale);
										$strXML .= "</graph>";
										$chartWidth = ($chart_baseWidth * count($records) > $chart_minWidth)?($chart_baseWidth * count($records)) : $chart_minWidth;
										$chartHeight = ($chart_baseHeight * 30  > $chart_minHeight)?($chart_baseHeight * 30) : $chart_minHeight;
										echo renderChart("charts/swf/FCF_Line.swf", "", $strXML, $protocol['protocol_name'] . "_checkingRecords", $chartWidth, $chartHeight);
									}else{ // Draw image chart
										$chartWidth = ($chart_baseWidth * count($records) > $chart_minWidth)?($chart_baseWidth * count($records)) : $chart_minWidth;
										if($chartWidth >= $chart_maxWidth){
											$chartWidth = $chart_maxWidth;
										}
										
										$chartHeight = ($chart_baseHeight * 30  > $chart_minHeight)?($chart_baseHeight * 30) : $chart_minHeight;
										if($chartHeight >= $chart_maxHeight){
											$chartHeight = $chart_maxHeight;
										}
										$chart_title = "Monitoring result for protocol " . $protocol['protocol_name'] . "(" . $protocol['protocol_port'] . ") - %s. Scale 1:" . $chart_valueScale ;
										$dataSet = new pData;
										// Define chart data
										
										$serie = $site_hostname . "-" . $protocol['protocol_name'] . "(" . $protocol['protocol_port'] . ")";
										$chart_title = sprintf($chart_title, "Day detail");
										
										$i = 0;
										$idxOfMax = 0;
										$idxOfMin = 0;
										foreach($records as $record){
											$dataSet->AddPoint(round($record['operating_time'] * 1000 * $chart_valueScale , $chart_decimalPrecision), $serie, substr($record['starting_time'], 11));
											if($record['operating_time'] > $records[$idxOfMax]['operating_time']){
												$idxOfMax = $i;
											}
											if($record['operating_time'] < $records[$idxOfMin]['operating_time']){
												$idxOfMin = $i;
											}
											$i ++;
										}
										if($records[$idxOfMax]['operating_time']*1000*$chart_valueScale < 1){
											echo "<b>All graph values are zero. We shouldn't draw it</b>";
											exit;
										}
										$dataSet->AddAllSeries();
										$dataSet->SetAbsciseLabelSerie();
										$dataSet->SetXAxisName("Start time");
										if($protocol['protocol_name'] == 'ICMP'){
 											$dataSet->SetYAxisName("Response Time(ms)");
										}else{
											$dataSet->SetYAxisName("Fetching Time(ms)");
										}
										// Initialize the chart
										$chart = new pChart($chartWidth + 70, $chartHeight + 30);										
										// set color for the line
										$chart->setColorPalette(0, 255, 15, 70);
										//$chart->reportWarnings("GD");
 										$chart->setFontProperties("Fonts/tahoma.ttf", 9);
										$chart->setGraphArea(70, 30, $chartWidth - 20, $chartHeight - 120 );
										$chart->drawGraphArea(255,255,255,TRUE);
										$chart->drawFilledRoundedRectangle(7, 7, $chartWidth -7, $chartHeight ,5,255,255,255);
 //										$chart->drawRoundedRectangle(5,5,$chartWidth - 5, $chartHeight - 5 ,5,230,230,230);
 										$chart->drawScale($dataSet->GetData(),$dataSet->GetDataDescription(), SCALE_ADDALLSTART0,0,0,255,TRUE,90,2);
 										$chart->drawGrid(4, TRUE, 230, 230, 230, 50);
										$chart->writeValues($dataSet->GetData(), $dataSet->GetDataDescription(), $serie);
 										// Draw the 0 line
 									 	$chart->setFontProperties("Fonts/tahoma.ttf",6);
 										$chart->drawTreshold(0,255,255,255,TRUE,TRUE);
 										// Draw the line
 										$chart->drawLineGraph($dataSet->GetData(),$dataSet->GetDataDescription(), $serie);
 										$chart->drawPlotGraph($dataSet->GetData(),$dataSet->GetDataDescription(),3,2,255,255,255);

 									 	$chart->setFontProperties("Fonts/tahoma.ttf",8);
										$chart->writeValues($dataSet->GetData(),$dataSet->GetDataDescription(), $site_hostname . "-" . $protocol['protocol_name'] . $protocol['protocol_port']);
 										// Finish the graph
										//$chart->setFontProperties("Fonts/tahoma.ttf", 10);
										//$chart->drawLegend(75,35,$dataSet->GetDataDescription(),255,255,255);
										$chart->setFontProperties("Fonts/tahoma.ttf",10);
										$chart->drawTitle($chartWidth/2, 20, $chart_title,50,50,50,585);
										$image_path = "tmp/" . $site_hostname . "-" . $protocol['protocol_name'] . "-" . $protocol['protocol_port'] . ".jpg";
										$randy = md5( uniqid (rand(), 1) );
										$chart->Render($image_path);
										sleep(3);
										echo "<div width=\"100%\"><img src=\"$image_path?$randy\" /></div>";
									}
								}
							}
						}
					}
				}
				break;
			case BY_MONTH:
				{
					// get all protocols
					$protocols = get_protocols($site_id, $link, $error);
					if($protocols === false){ // failed to get protocol
						echo "<div align=\"center\" width=\"100%\"><h3>$error</h3></div>";
						exit;
					}else{
						if(count($protocols) < 1){ // there is no protocol for this site
							echo "<div align=\"center\" width=\"100%\"><h3>There has no protocol configured for this site</h3></div>";
							exit;
						}
						foreach($protocols as $protocol){ // draw one chart for each protocol
							$error = '';
							$records = get_checking_records_by_month($site_id, $protocol['protocol_id'], $year, $month, $link, $error);
							if($records === false){
								echo "<div align=\"center\" width=\"100%\"><h3>$error</h3></div>";
								exit;
							}else{
								if(count($records) < 1){ // there is no record for this site and the protocol
									echo "<div align=\"center\" width=\"100%\"><h3>There has no checking record for protocol: " . $protocol['protocol_name'] . "</h3></div>";
									exit;
								}else{
									if($graph == 'flash'){
										$minValue = 0;
										$maxValue = 0;
										echo "<SCRIPT LANGUAGE=\"Javascript\" SRC=\"charts/js/FusionCharts.js\"></SCRIPT>";
										// draw chart now
										$chart_title = "Monitoring result for protocol " . $protocol['protocol_name']
												. ". Scale: 1:" . $chart_valueScale;
										$sub_title = "Month detail";
										$strXML = "<graph caption='" . $chart_title
												. "' formatNumberScale='" . $chart_formatNumberScale
												. "' decimalPrecision='" . $chart_decimalPrecision
												. "' rotateNames='" . $chart_rotateNames;
										if($protocol['protocol_name'] == 'ICMP'){
											$strXML .= "' yAxisName= 'Response Time(ms)";
										}else{
											$strXML .= "' yAxisName= 'Fetching Time(ms)";
										}
										$strXML .= "' xAxisName= 'Start time"
											. "' baseFontSize='" . $chart_baseFontSize
											. "' yAxisMinValue='%s"
											. "'>";
											;
										$minValue = $records[0]['operating_time'];
										foreach($records as $record){
	      									$strXML .= "<set name='" . substr($record['starting_time'], 11) . "' value='" . ($record['operating_time']* $chart_valueScale) . "' colo='" . getFCColor() . "' />";
	      									//find the minimum total time to identify the yAxisMinValue
	      									if($record['operating_time'] < $minValue){
	      										$minValue = $record['operating_time'];
	      									}
	      									//find the maximum total time to identify the yAxisMaxValue
											if($record['operating_time'] > $maxValue){
	      										$maxValue = $record['operating_time'];
	      									}
										}
										$strXML = sprintf($strXML, ($minValue/2) * $chart_valueScale);
										$strXML .= "</graph>";
									}else{
										$chartWidth = ($chart_baseWidth * count($records) > $chart_minWidth)?($chart_baseWidth * count($records)) : $chart_minWidth;
										if($chartWidth >= $chart_maxWidth){
											$chartWidth = $chart_maxWidth;
										}
										$chartHeight = ($chart_baseHeight * 30  > $chart_minHeight)?($chart_baseHeight * 30) : $chart_minHeight;
										if($chartHeight >= $chart_maxHeight){
											$chartHeight = $chart_maxHeight;
										}
										$chart_title = "Monitoring result for protocol " . $protocol['protocol_name'] . "(" . $protocol['protocol_port'] . ") - %s. Scale 1:" . $chart_valueScale ;
										$dataSet = new pData;
										// Define chart data
										$serie = $site_hostname . "-" . $protocol['protocol_name'] . "(" . $protocol['protocol_port'] . ")";
										$chart_title = sprintf($chart_title, "Day detail");
										
										$i = 0;
										$idxOfMax = 0;
										$idxOfMin = 0;
										foreach($records as $record){
											$dataSet->AddPoint(round($record['operating_time'] * 1000 * $chart_valueScale , $chart_decimalPrecision), $serie, substr($record['starting_time'], 11));
											if($record['operating_time'] > $records[$idxOfMax]['operating_time']){
												$idxOfMax = $i;
											}
											if($record['operating_time'] < $records[$idxOfMin]['operating_time']){
												$idxOfMin = $i;
											}
											$i ++;
										}
										
										if($records[$idxOfMax]['operating_time']*1000*$chart_valueScale < 1){
											echo "<b>All graph values are zero. We shouldn't draw it</b>";
											exit;
										}
										
										$dataSet->AddAllSeries();
										$dataSet->SetAbsciseLabelSerie();
										$dataSet->SetXAxisName("Start time");
										if($protocol['protocol_name'] == 'ICMP'){
 											$dataSet->SetYAxisName("Response Time(ms)");
										}else{
											$dataSet->SetYAxisName("Fetching Time(ms)");
										}
										// Initialize the chart
										$chart = new pChart($chartWidth + 70, $chartHeight + 30);
										// set color for the line
										$chart->setColorPalette(0, 255, 15, 70);
										//$chart->reportWarnings("GD");
 										$chart->setFontProperties("Fonts/tahoma.ttf", 9);
										$chart->setGraphArea(70, 30, $chartWidth - 20, $chartHeight - 120 );
										$chart->drawGraphArea(255,255,255,TRUE);
										$chart->drawFilledRoundedRectangle(7, 7, $chartWidth -7, $chartHeight ,5,255,255,255);
 //										$chart->drawRoundedRectangle(5,5,$chartWidth - 5, $chartHeight - 5 ,5,230,230,230);
 										$chart->drawScale($dataSet->GetData(),$dataSet->GetDataDescription(), SCALE_ADDALLSTART0,0,0,255,TRUE,90,2);
 										$chart->drawGrid(4, TRUE, 230, 230, 230, 50);
										$chart->writeValues($dataSet->GetData(), $dataSet->GetDataDescription(), $serie);
 										// Draw the 0 line
 									 	$chart->setFontProperties("Fonts/tahoma.ttf",6);
 										$chart->drawTreshold(0,255,255,255,TRUE,TRUE);
 										// Draw the line
 										$chart->drawLineGraph($dataSet->GetData(),$dataSet->GetDataDescription(), $serie);
 										$chart->drawPlotGraph($dataSet->GetData(),$dataSet->GetDataDescription(),3,2,255,255,255);

 									 	$chart->setFontProperties("Fonts/tahoma.ttf",8);
										$chart->writeValues($dataSet->GetData(),$dataSet->GetDataDescription(), $site_hostname . "-" . $protocol['protocol_name'] . $protocol['protocol_port']);
 										// Finish the graph
										//$chart->setFontProperties("Fonts/tahoma.ttf", 10);
										//$chart->drawLegend(75,35,$dataSet->GetDataDescription(),255,255,255);
										$chart->setFontProperties("Fonts/tahoma.ttf",10);
										$chart->drawTitle($chartWidth/2, 20, $chart_title,50,50,50,585);
										$image_path = "tmp/" . $site_hostname . "-" . $protocol['protocol_name'] . "-" . $protocol['protocol_port'] . ".jpg";
										$randy = md5( uniqid (rand(), 1) );
										$chart->Render($image_path);
										sleep(3);
										echo "<div width=\"100%\"><img src=\"$image_path?$randy\" /></div>";																			}
									}
								}
							}
						}
					}
				break;
			case BY_YEAR:
				break;
			default:
				break;
		}

	}
?>
